package com.cyf.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * Http发送工具类
 * Created by hfy on 2017/12/5.
 */
public class HttpUtils {

    private static final int TIME_OUT_SECONDS = 6;
    public static final String UPLOADCARFEE_URL = "http://cheyifu2016.com:8892/openapi/uploadCarFee";
    public static final String QRCODE_URL = ":8080/wexin/login.action?uuid=";

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static String postJson(String url, String json, int timeOutSeconds) {
        logger.info("请求url：{}", url);
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            config(httpPost, timeOutSeconds);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            ByteArrayEntity byteArrayEntity = new ByteArrayEntity(json.getBytes("UTF-8"));
            httpPost.setEntity(byteArrayEntity);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {

                if (response != null) {
                    HttpEntity rspEntity = response.getEntity();
                    if (rspEntity != null) {
                        String resultStr = EntityUtils.toString(rspEntity, "UTF-8");
                        logger.info("返回数据：{}", resultStr);
                        return resultStr;
                    }
                }
            }
        } catch (IOException e) {
            logger.info("发送数据失败：{}", e.getMessage());
        } catch (Exception e) {
            logger.error("发送数据异常：{}", e);
        } finally {
            try {
                //关闭流并释放资源
                httpClient.close();
            } catch (IOException e) {
                logger.error("关闭流异常：{}", e);
            }
        }
        return null;
    }

    public static String postJson(String url, String json) {
        return postJson(url, json, TIME_OUT_SECONDS);
    }


    public static String postMap(String url, Map<String, String> map, int timeOutSeconds) {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        return postMap(url, map, timeOutSeconds, httpClient);
    }

    private static String postMap(String url, Map<String, String> map, int timeOutSeconds, CloseableHttpClient httpClient) {
        logger.info("请求url：{}", url);
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost post = new HttpPost(url);
            config(post, timeOutSeconds);
            String urlEncoding;
            if (map != null) {
                logger.info("请求数据：{}", map);
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> param : map.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
                    paramList.add(pair);
                }
                post.setEntity(new UrlEncodedFormEntity(paramList, "utf-8"));
            }
            response = httpClient.execute(post, HttpClientContext.create());

            HttpEntity rspEntity = response.getEntity();
            if (rspEntity != null) {
                responseText = EntityUtils.toString(rspEntity);
            }
            logger.info("返回数据：{}", responseText);
        } catch (Exception e) {
            logger.error("post数据异常: {}", e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                logger.error("post发送数据，关闭response异常: {}", e.getMessage());
            }
        }
        return responseText;
    }





    public static String postMap(String url, Map map) {
        return postMap(url, map, TIME_OUT_SECONDS);
    }

    private static void config(HttpPost httpPost, int timeOut) {
        timeOut = timeOut * 1000;
        // 配置请求的超时设置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(timeOut)
                .setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
        httpPost.setConfig(requestConfig);

        httpPost.addHeader("Connection", "close");
    }






    public static String get(String url, HashMap<String, String> paramsMap, int timeOut) {
        logger.info("请求url：{}", url);
        String responseText = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {

            String params = "";
            if (paramsMap != null) {
                StringBuilder stringBuilder = new StringBuilder();
                Set<Map.Entry<String, String>> entries = paramsMap.entrySet();
                for (Map.Entry<String, String> entry : entries) {
                    String value = URLEncoder.encode(entry.getValue(), "utf-8");
                    stringBuilder.append(entry.getKey()).append("=").append(value).append("&");
                }
                if (paramsMap.size() > 0) {
                    stringBuilder.insert(0, "?");
                    params = stringBuilder.substring(0, stringBuilder.lastIndexOf("&"));
                }
            }

            logger.info("请求地址：{}", url + params);
            HttpGet httpGet = new HttpGet(url + params);

            //设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(timeOut * 1000).setConnectTimeout(timeOut * 1000).build();
            httpGet.setConfig(requestConfig);

            response = httpClient.execute(httpGet);

            HttpEntity rspEntity = response.getEntity();
            if (rspEntity != null) {
                responseText = EntityUtils.toString(rspEntity);
            }
            logger.info("返回数据：{}", responseText);

        } catch (Exception e) {
            logger.error("get数据异常: {}", e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                logger.error("get发送数据，关闭response异常: {}", e.getMessage());
            }
        }
        return responseText;
    }

}
